#!/usr/bin/env bash

main() {
	local SCRIPT_DIR
	SCRIPT_DIR="$(dirname "$(realpath "$0")")"

	local TEMP
	if ! TEMP="$(getopt -o "hu" -l "help,unset" -n "$0" -- "$@")"; then
		return
	fi
	eval set -- "$TEMP"

	local RSDK_OPTION_UNSET="${RSDK_OPTION_UNSET:-false}"

	while true; do
		TEMP="$1"
		shift
		case "$TEMP" in
		-h | --help)
			TEMP="$(basename "$0")"
			rsdk help "${TEMP#rsdk-}"
			return
			;;
		-u | --unset)
			RSDK_OPTION_UNSET="true"
			;;
		--)
			break
			;;
		*)
			error "$EXIT_UNKNOWN_OPTION" "$TEMP"
			;;
		esac
	done

	local FIELD="$1" config_files=(
		"$SCRIPT_DIR/../../share/rsdk/configs/rsdk.json"
	)

	if [[ -f .rsdk.json ]]; then
		config_files+=(.rsdk.json)
	fi

	case $# in
	1)
		if [[ $RSDK_OPTION_UNSET == "true" ]]; then
			local RSDK_TEMP_JSON
			RSDK_TEMP_JSON="$(mktemp)"
			jq -er --arg field "$FIELD" 'delpaths([$field / "."])' .rsdk.json >"$RSDK_TEMP_JSON"
			mv "$RSDK_TEMP_JSON" .rsdk.json
		else
			jq -ers --arg field "$FIELD" 'reduce .[] as $i ({}; . * $i) |
				if $field == "." then . else getpath($field / ".") end |
				if type == "array" then .[] else . end' "${config_files[@]}"
		fi
		;;
	2)
		local RSDK_TEMP_JSON VALUE="$2"
		RSDK_TEMP_JSON="$(mktemp)"

		if ! [[ -f .rsdk.json ]]; then
			echo "{}" > .rsdk.json
		fi

		jq -er --arg field "$FIELD" --arg value "$VALUE" 'setpath($field / "."; $value)' .rsdk.json >"$RSDK_TEMP_JSON"
		mv "$RSDK_TEMP_JSON" .rsdk.json
		;;
	*)
		"$0" --help
		return
		;;
	esac
}

main "$@"
